<template>
  <el-drawer
    :append-to-body="true"
    title="经办人"
    v-model="visible"
    class="set_promoter"
    :show-close="false"
    :size="550"
    :before-close="savePromoter"
  >
    <div class="demo-drawer__content">
      <div class="promoter_content drawer_content">
        <el-radio-group v-model="radio1">
          <el-radio-button :value="1">基础设置</el-radio-button>
          <!-- <el-radio-button :value="2">表单权限</el-radio-button> -->
          <el-radio-button :value="3">操作权限</el-radio-button>
        </el-radio-group>
        <div class="personnel_box" v-show="radio1 == 1">
          <div class="who_can_submit">经办人范围设置</div>
          <div class="per_content">
            <span class="title">按人员选取</span>
            <el-button type="primary" link @click="addPromoter">选取</el-button>
            <el-button type="primary" link @click="clearData(0)">
              清除
            </el-button>
            <div class="name_box">
              <el-tag
                v-for="(u, i) in flowPromoter"
                :key="i"
                closable
                type="info"
                @close="delUser(0, i)"
              >
                {{ u.name }}
              </el-tag>
            </div>
          </div>
          <div class="per_content">
            <span class="title">按职务选取</span>
            <el-button type="primary" link @click="addDept(1)">选取</el-button>
            <el-button type="primary" link @click="clearData(1)">
              清除
            </el-button>
            <div class="name_box">
              <el-tag
                v-for="(u, i) in flowDuties"
                :key="i"
                closable
                type="info"
                @close="delUser(1, i)"
              >
                {{ u.name }}
              </el-tag>
            </div>
          </div>
          <div class="per_content">
            <span class="title">按部门选取</span>
            <el-button type="primary" link @click="addDept(2)">选取</el-button>
            <el-button type="primary" link @click="clearData(2)">
              清除
            </el-button>
            <div class="name_box">
              <el-tag
                v-for="(u, i) in flowDept"
                :key="i"
                closable
                type="info"
                @close="delUser(2, i)"
              >
                {{ u.name }}
              </el-tag>
            </div>
          </div>
        </div>
        <div class="table_box" v-show="radio1 == 2">
          <el-table
            :data="tableData"
            border
            stripe
            height="calc(100vh - 200px)"
            :header-cell-style="{ backgroundColor: '#f2f2f2' }"
          >
            <el-table-column label="字段名称" prop="fieldName" align="center" />
            <el-table-column align="center">
              <template #header>
                <el-checkbox
                  v-model="tableCheck.readable"
                  :indeterminate="tableCheck.isReadableIndeterminate"
                  @change="handleReadableChange"
                >
                  可见
                </el-checkbox>
              </template>
              <template #default="{ row }">
                <el-checkbox v-model="row.readable" @change="readableChange" />
              </template>
            </el-table-column>
            <el-table-column align="center">
              <template #header>
                <el-checkbox
                  v-model="tableCheck.writable"
                  :indeterminate="tableCheck.isWritableIndeterminate"
                  @change="handleWritableChange"
                >
                  编辑
                </el-checkbox>
              </template>
              <template #default="{ row }">
                <el-checkbox v-model="row.writable" @change="writableChange" />
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="operation_box" v-show="radio1 == 3">
          <!-- <div :class="[operationInfo.approval ? '' : 'operation_content']">
            <span class="title">是否参与审批</span>
            <el-radio-group
              v-model="operationInfo.approval"
              @change="radioChange($event, 1)"
            >
              <el-radio :value="true">参与</el-radio>
              <el-radio :value="false">不参与</el-radio>
            </el-radio-group>
          </div>
          <div class="operation_content" v-show="operationInfo.approval">
            <span class="title"></span>
            <el-checkbox
              v-model="operationInfo.signOpinions"
              label="参与审批时需要签署意见"
            />
          </div> -->
          <div class="operation_content">
            <span class="title">审批方式</span>
            <el-radio-group
              v-model="operationInfo.approvalType"
              @change="auditChange"
            >
              <el-radio :value="1">单人审批</el-radio>
              <!-- <el-radio :value="2">多人审批</el-radio> -->
              <el-radio :value="3">无需审批</el-radio>
            </el-radio-group>
          </div>
          <div class="operation_content" v-if="operationInfo.approvalType == 2">
            <span class="title" style="width: 210px"
              >多人审批时采用的审批方式</span
            >
            <el-radio-group v-model="operationInfo.approvalCondition">
              <el-radio :value="1" style="width: 100%"
                >会签(需所有审批人同意)</el-radio
              >
              <el-radio :value="2" style="width: 100%"
                >或签(一名审批人同意即可)</el-radio
              >
              <el-radio :value="3" style="width: 100%"
                >依次审批(按需所有审批人同意)</el-radio
              >
            </el-radio-group>
          </div>
          <div class="operation_content">
            <span class="title">审批时是否签署意见</span>
            <el-radio-group v-model="operationInfo.signOpinions">
              <el-radio :value="true">是</el-radio>
              <el-radio :value="false">否</el-radio>
            </el-radio-group>
          </div>
          <div class="operation_content">
            <span class="title">是否可结束流程</span>
            <el-radio-group v-model="operationInfo.endProcess">
              <el-radio :value="true">可结束</el-radio>
              <el-radio :value="false">不可结束</el-radio>
            </el-radio-group>
          </div>
          <div class="operation_content">
            <span class="title">是否可退回流程</span>
            <el-radio-group
              v-model="operationInfo.returnProcess"
              @change="radioChange($event, 2)"
            >
              <el-radio :value="true">可退回</el-radio>
              <el-radio :value="false">不可退回</el-radio>
            </el-radio-group>
          </div>
          <!-- <div class="operation_content" v-show="operationInfo.returnProcess">
            <span class="title">退回方式</span>
            <el-radio-group v-model="operationInfo.returnNodeId">
              <el-radio :value="-1">退回到上一个节点</el-radio>
              <el-radio :value="100000">退回至发起人</el-radio>
            </el-radio-group>
          </div> -->
          <div class="operation_content">
            <span class="title">是否可撤回流程</span>
            <el-radio-group v-model="operationInfo.withdrawalProcess">
              <el-radio :value="true">可撤回</el-radio>
              <el-radio :value="false">不可撤回</el-radio>
            </el-radio-group>
          </div>
          <div class="operation_content">
            <span class="title">是否可续接流程</span>
            <el-radio-group v-model="operationInfo.continue" @change="radioChange($event, 3)">
              <el-radio :value="true">可续接</el-radio>
              <el-radio :value="false">不可续接</el-radio>
            </el-radio-group>
          </div>
          <template v-if="operationInfo.continue">
            <div class="operation_content">
              <span class="title">续接流程</span>
              <el-select
                v-model="operationInfo.continueFlowId"
                placeholder="请选择"
              >
                <el-option
                  v-for="u in continueFlowList"
                  :key="u.id"
                  :label="u.name"
                  :value="u.id"
                ></el-option>
              </el-select>
            </div>
          </template>
        </div>
      </div>
      <div class="demo-drawer__footer clear">
        <el-button type="primary" @click="savePromoter">确 定</el-button>
        <el-button @click="closeDrawer">取 消</el-button>
      </div>
      <!-- 按人员选取 -->
      <FlowDialogTeacherSelection
        :importVisible="promoterVisible"
        :checkedList="checkedPromoterList"
        @closeDialog="surePromoter"
      />
      <!-- 按部门职务选取 -->
      <FlowDialogDeptDutiesSelection
        :importVisible="deptDutiesVisible"
        :checkedList="checkedDeptDutiesList"
        :type="type"
        @closeDialog="sureDeptDuties"
      />
    </div>
  </el-drawer>
</template>
<script setup>
import $func from "@/utils/flow";
import { useFlowStore } from "@/stores/flow";
import { continueFlowListApi } from "@/services/api/flow";
let store = useFlowStore();
let { setApproverConfig, setApprover } = store;
let approverDrawer = computed(() => store.approverDrawer);
let approverConfig1 = computed(() => store.approverConfig1);
let formFiledList = computed(() => store.formFiledList);
let visible = computed({
  get() {
    return approverDrawer.value;
  },
  set() {
    closeDrawer();
  },
});
let props = defineProps({
  nodeConfig: {
    type: Object,
    default: () => ({}),
  },
});

const state = reactive({
  radio1: 1,
  type: 1, //1为职务，2为部门
  approverConfig: {},
  flowPromoter: [],
  flowDuties: [],
  flowDept: [],
  checkedDeptDutiesList: [],
  checkedPromoterList: [],
  promoterVisible: false,
  deptDutiesVisible: false,

  tableData: [],
  tableCheck: {
    readable: false,
    writable: false,
    isReadableIndeterminate: true,
    isWritableIndeterminate: true,
  },
  operationInfo: {
    approval: true, //是否参与审批
    signOpinions: true, //参与审批时需要签署意见
    approvalType: 1, //审批方式  1单人审批  2多人审批 3无需审批   默认传0
    approvalCondition: 0, // 多人审批时审批方式  1(需所有审批人同意)  2或签一名审批人同意即可) 3依次审批(按顺序依次审批)  默认传0
    endProcess: false, //是否可结束流程
    returnProcess: false, //是否可退回流程
    returnNodeId: "", //可退回节点
    withdrawalProcess: false, //是否可撤回流程
    continue: false, //是否可续接流程
  },
  parentNodeList: [],
  flowList: [],
  continueFlowList:[]
});
const {
  radio1,
  type,
  flowPromoter,
  flowDuties,
  flowDept,
  checkedDeptDutiesList,
  checkedPromoterList,
  promoterVisible,
  deptDutiesVisible,
  tableData,
  tableCheck,
  operationInfo,
  parentNodeList,
  flowList,
  continueFlowList,
} = toRefs(state);

watch(approverConfig1, (val) => {
  if (approverDrawer.value) {
    state.radio1 = 1;
    //审批人员
    state.flowPromoter = [];
    state.flowDuties = [];
    state.flowDept = [];
    state.approverConfig = val.value;
    val.value.nodeUserList.forEach((u) => {
      if (u.type == 1) {
        state.flowPromoter.push(u);
      } else if (u.type == 2) {
        state.flowDuties.push(u);
      } else {
        state.flowDept.push(u);
      }
    });
    // 表单权限
    if (val.value.formPermissions.length > 0) {
      let arr = val.value.formPermissions;
      let list = JSON.parse(JSON.stringify(formFiledList.value));
      list.forEach((item) => {
        let obj = arr.find((v) => v.fieldId == item.fieldId);
        if (obj) {
          item.readable = obj.readable;
          item.writable = obj.writable;
        } else {
          item.readable = true;
          item.writable = false;
        }
      });
      state.tableData = list;
    } else {
      state.tableData = JSON.parse(JSON.stringify(formFiledList.value));
    }
    readableChange();
    writableChange();
    //可退回节点列表
    getReturnable(state.approverConfig.nodeId);
    // 操作权限
    state.operationInfo = state.approverConfig.operationInfo;
    if (!state.operationInfo.approval) {
      state.operationInfo.approval = true;
    }
    if (!state.operationInfo.returnNodeId) {
      state.operationInfo.returnNodeId = state.parentNodeList[0].nodeId;
    }
    if (!state.operationInfo.continue) {
      state.operationInfo.continue = false;
    }
    if (state.operationInfo.approvalType == undefined) {
      state.operationInfo.approvalType = 1;
      state.operationInfo.approvalCondition = 0;
    }
    if (state.operationInfo.continue) {
      getContinueFlowList();
    }
  }
});

/**
 * 选取人员
 */
function addPromoter() {
  state.checkedPromoterList = state.flowPromoter;
  state.promoterVisible = true;
}
/**
 * 确认人员
 */
function surePromoter(data) {
  state.promoterVisible = false;
  if (!data) return; //点击关闭窗口
  state.flowPromoter = data;
}
/**
 * 选取部门职务
 */
function addDept(type) {
  state.type = type;
  if (type == 1) {
    state.checkedDeptDutiesList = state.flowDuties;
  } else {
    state.checkedDeptDutiesList = state.flowDept;
  }
  state.deptDutiesVisible = true;
}
/**
 * 确认部门职务
 */
function sureDeptDuties(data) {
  state.deptDutiesVisible = false;
  if (!data) return; //点击关闭窗口
  if (state.type == 1) {
    state.flowDuties = data;
  } else {
    state.flowDept = data;
  }
}
/**
 * 清除数据
 */
function clearData(type) {
  if (type == 0) {
    state.flowPromoter = [];
  } else if (type == 1) {
    state.flowDuties = [];
  } else {
    state.flowDept = [];
  }
}
/**
 * 单个清除数据
 */
function delUser(type, index) {
  if (type == 0) {
    state.flowPromoter.splice(index, 1);
  } else if (type == 1) {
    state.flowDuties.splice(index, 1);
  } else {
    state.flowDept.splice(index, 1);
  }
}
/**
 * 改变全部可读权限
 */
function handleReadableChange(val) {
  state.tableData.forEach((u) => {
    u.readable = val;
  });
  state.tableCheck.isReadableIndeterminate = false;
}
/**
 * 改变全部编辑权限
 */
function handleWritableChange(val) {
  state.tableData.forEach((u) => {
    u.writable = val;
  });
  state.tableCheck.isWritableIndeterminate = false;
}
/**
 * 改变单个可读权限
 */
function readableChange() {
  let allReadableTrue = state.tableData.every((item) => item.readable === true);
  let allReadableFalse = state.tableData.every(
    (item) => item.readable === false,
  );
  if (allReadableTrue) {
    state.tableCheck.readable = true;
    state.tableCheck.isReadableIndeterminate = false;
  } else if (allReadableFalse) {
    state.tableCheck.readable = false;
    state.tableCheck.isReadableIndeterminate = false;
  } else {
    state.tableCheck.readable = false;
    state.tableCheck.isReadableIndeterminate = true;
  }
}
/**
 * 改变单个编辑权限
 */
function writableChange() {
  let allWritableTrue = state.tableData.every((item) => item.writable === true);
  let allWritableFalse = state.tableData.every(
    (item) => item.writable === false,
  );
  if (allWritableTrue) {
    state.tableCheck.writable = true;
    state.tableCheck.isWritableIndeterminate = false;
  } else if (allWritableFalse) {
    state.tableCheck.writable = false;
    state.tableCheck.isWritableIndeterminate = false;
  } else {
    state.tableCheck.writable = false;
    state.tableCheck.isWritableIndeterminate = true;
  }
}
/**
 * 修改是否参与审批 type1
 * 修改是否可退回流程 type2
 */
function radioChange(val, type) {
  if (!val) {
    if (type == 1) {
      state.operationInfo.signOpinions = false;
      state.operationInfo.approvalType = 0;
      state.operationInfo.approvalCondition = 0;
    } else if (type == 2) {
      state.operationInfo.returnNodeId = "";
    }

  } else {
    if (type == 1) {
      state.operationInfo.signOpinions = true;
    } else if (type == 2) {
      state.operationInfo.returnNodeId = state.parentNodeList[0].nodeId;
    }else if (type == 3) {
      if(state.operationInfo.continue){
        getContinueFlowList();
      }
    }
  }
}
function getContinueFlowList() {
  continueFlowListApi().then((res) => {
    state.continueFlowList = res.data;
  });
}
function auditChange(val) {
  if (val == 1) {
    state.operationInfo.approvalCondition = 0;
  } else {
    state.operationInfo.approvalCondition = 1;
  }
}
/**
 * 获取所有审批流程路径id和name集合
 * 不包含路由和条件节点
 */
function extractPaths(node, path = [], paths = []) {
  let currentPath = [...path]; // 复制当前路径以避免引用问题

  // 如果当前节点有 nodeId，将其添加到路径(除路由节点)
  if (node.nodeId != null) {
    currentPath.push({ nodeId: node.nodeId, nodeName: node.nodeName });
  }

  // 检查当前节点类型
  if (node.type === 4 && node.conditionNodes) {
    // 如果是路由节点且有条件节点
    let allConditionPaths = []; // 存储所有条件分支生成的路径

    // 遍历所有条件节点
    node.conditionNodes.forEach((condition) => {
      let conditionPath = [...currentPath]; // 创建条件路径
      // 递归处理条件子节点
      if (condition.childNode) {
        extractPaths(condition.childNode, conditionPath, allConditionPaths);
      } else {
        // 条件没有子节点，将路径添加到结果中
        allConditionPaths.push(conditionPath);
      }
    });

    // 对于每个条件生成的路径，将路由节点的共有 childNode 添加
    allConditionPaths.forEach((conditionPath) => {
      if (node.childNode) {
        extractPaths(node.childNode, conditionPath, paths);
      } else {
        paths.push(conditionPath);
      }
    });
  } else if (node.childNode) {
    // 存在普通子节点
    extractPaths(node.childNode, currentPath, paths);
  } else {
    // 没有子节点，将当前路径添加到总路径数组
    paths.push(currentPath);
  }

  return paths;
}
/**
 * 获取可退回节点列表
 * 筛选出包含该nodeId的路径，然后提取该节点的所有父节点
 */
function getReturnable(nodeId) {
  const flowList = extractPaths(props.nodeConfig);
  // 创建一个Set来存储已经出现过的nodeId
  const seenNodeIds = new Set();

  let result = [];
  // 筛选包含nodeId的子数组
  flowList.forEach((subArray) => {
    // 查找nodeId在子数组中的索引
    const index = subArray.findIndex((obj) => obj.nodeId === nodeId);
    // 如果找到了nodeId，则提取位置之前的元素（不包括nodeId位置的元素）
    if (index !== -1) {
      // 提取位置之前的元素
      const extractedElements = subArray.slice(0, index);
      // 将提取的元素添加到结果数组中，但只添加那些nodeId尚未出现过的元素
      extractedElements.forEach((u) => {
        if (!seenNodeIds.has(u.nodeId)) {
          seenNodeIds.add(u.nodeId);
          result.push(u);
        }
      });
    }
  });
  // 对结果数组进行倒序排列
  // result.reverse();
  state.parentNodeList = result;
}
/**
 * 保存
 */
function savePromoter() {
  const summarizeData = state.flowPromoter.concat(
    state.flowDuties,
    state.flowDept,
  );
  let teach_count =
    state.flowDuties.reduce((a, b) => {
      return a + b.teach_count;
    }, 0) +
    state.flowDept.reduce((a, b) => {
      return a + b.teach_count;
    }, 0) +
    state.flowPromoter.length;
  if (teach_count < 2 && state.operationInfo.approvalType == 2) {
    return ElMessage({
      message: "多人审批时至少选择两个经办人",
      type: "error",
    });
  }
  state.approverConfig.nodeUserList = summarizeData;
  state.approverConfig.formPermissions = state.tableData;
  if (!state.operationInfo.continue) {
    state.operationInfo.continueFlowId = "";
  }
  state.approverConfig.operationInfo = state.operationInfo;
  state.approverConfig.error = !$func.setApproverStr(state.approverConfig);
  setApproverConfig({
    value: state.approverConfig,
    flag: true,
    id: approverConfig1.value.id,
  });
  closeDrawer();
}
function closeDrawer() {
  setApprover(false);
}
</script>
<style lang="scss" scoped>
.set_promoter {
  .promoter_content {
    padding: 20px 20px 0;
    :deep(.el-radio-button__inner) {
      width: 255px;
    }
  }
  .personnel_box {
    .who_can_submit {
      margin: 20px 0 6px 0;
      font-size: 14px;
    }
    .per_content {
      .title {
        display: inline-block;
        font-size: 14px;
        margin: 8px 20px 0 0;
      }
      .name_box {
        width: 100%;
        height: 130px;
        margin-top: 5px;
        padding: 0 4px 4px 0;
        border: 1px solid #dcdfe6;
        font-size: 14px;
        border-radius: 5px;
        overflow-y: auto;
        .el-tag {
          margin: 4px 0 0 4px;
        }
      }
    }
  }
  .table_box {
    margin-top: 20px;
  }
  .operation_box {
    margin-top: 20px;
    .operation_content {
      margin-bottom: 10px;
      .return_name {
        margin-right: 10px;
        font-size: 14px;
      }
    }
    .title {
      display: inline-block;
      width: 144px;
      margin-bottom: 10px;
      font-size: 15px;
      font-weight: 700;
    }
  }
}
</style>
